package com.stxx.stiot2.service.impl;

import cn.hutool.core.util.StrUtil;
import com.stxx.framwork.constants.LogicType;
import com.stxx.framwork.domain.model.PageQuery;
import com.stxx.framwork.domain.model.PageResult;
import com.stxx.framwork.tran.TranUtils;
import com.stxx.framwork.utils.StoreUtils;
import com.stxx.stiot2.domain.Alarm;
import com.stxx.stiot2.domain.Device;
import com.stxx.stiot2.domain.Terminal;
import com.stxx.stiot2.service.AlarmService;
import com.stxx.stiot2.service.tran.TerminalTranService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.sql.SqlBuilder;

import java.sql.SQLException;
import java.util.*;

/**
 * @author Fuzhenlei
 * @date 2025/01/15 16:41
 */
@Component
public class AlarmServiceImpl implements AlarmService {
    private static final String tranField = "terminalCode";
    @Inject
    StoreUtils storeUtils;
    @Inject
    TerminalTranService terminalTranService;

    @Init
    public void init(){
        this.configLogic(Alarm::getName, LogicType.LIKE);
    }

    @Override
    public Alarm queryById(String id) {
        try {
            Alarm alarm = storeUtils.selectById(id,Alarm.class);
            TranUtils.build().add(tranField,terminalTranService).tran(alarm);
            return alarm;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int insert(Alarm bean) throws SQLException {
        if(bean.getId()==null){
            bean.setId(UUID.randomUUID().toString().replace("-",""));
        }
        validEntityBeforeSave(bean);
        return storeUtils.insert(bean);
    }

    @Override
    public int update(Alarm bean) throws SQLException {
        validEntityBeforeSave(bean);
        return storeUtils.update(bean);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Alarm bean){

    }



    @Override
    public int delete(String name) throws SQLException {
        return storeUtils.delete(Alarm.class,name);
    }

    @Override
    public int deleteByIds(String[] ids) throws SQLException {
        return storeUtils.deleteByIds(Alarm.class, ids);
    }

    @Override
    public List<Alarm> list(Alarm obj) throws SQLException {
        List<Alarm> list = storeUtils.selectList(Alarm.class,obj);
        TranUtils.build().add(tranField,terminalTranService).tran(list);
        return list;
    }

    @Override
    public PageResult<Alarm> pageList(Alarm obj, PageQuery pageQuery) throws SQLException {
        PageResult<Alarm> result = storeUtils.selectPageList(Alarm.class,obj,pageQuery);
        TranUtils.build().add(tranField,terminalTranService).tran(result.getData());
        return result;
    }

    @Override
    public PageResult<Alarm> pageListByDeviceId(String deviceId, PageQuery pageQuery) throws SQLException {
        SqlBuilder sb = new SqlBuilder();
        sb.append("from ").append(StoreUtils.getTableName(Alarm.class))
                .append(" a left join ")
                .append(StoreUtils.getTableName(Terminal.class)).append(" t on t.code = a.terminal_code")
                .append(" where a.cleared = 0 and t.device_id = ?",deviceId);
        sb.backup();
        sb.insert("select a.* ");
        if(StrUtil.isNotEmpty(pageQuery.getOrderByColumn())){
            if(StrUtil.isBlank(pageQuery.getIsAsc())){
                pageQuery.setIsAsc("asc");
            }
            sb.append(" order by ")
                    .append(pageQuery.getOrderByColumn())
                    .append(" ")
                    .append(pageQuery.getIsAsc());
        }
        sb.append(" limit ?,? ", (pageQuery.getPageNum()-1)*pageQuery.getPageSize(),pageQuery.getPageSize()); //分页获取列表

        List<Alarm> list = storeUtils.sql(sb).queryRowList(Alarm.class);
        //回滚（可以复用备份前的代码构建）
        sb.restore();
        sb.insert("select count(*)  ");
        //查询总数
        Long total = Long.parseLong(storeUtils.sql(sb).queryValue().toString());
        PageResult<Alarm> pageResult = new PageResult(list,total);
        return pageResult;
    }
}
